package com.test.springai.controller;

import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 8/20/25 8:11 AM
 * @modifiedBy:
 * @version: 1.0
 */
@RestController
@Slf4j
public class SpeechVoiceController {
  @Autowired private DashScopeSpeechSynthesisModel speechSynthesisModel;

  private static final String TEXT = "床前明月光，疑似地上霜，举头望明月，低头思故乡";
  private static final String FILE_PATH = "/home/lzy";

  @GetMapping("/tts")
  public void tts() {
    // 使用构建器模式创建实例并设置参数
    DashScopeSpeechSynthesisOptions options =
        DashScopeSpeechSynthesisOptions.builder()
            .withSpeed(1.0)
            .withPitch(0.9)
            .withVolume(60)
            .build();
    final SpeechSynthesisResponse response =
        speechSynthesisModel.call(new SpeechSynthesisPrompt(TEXT, options));
    File file = new File(FILE_PATH + "/output.mp3");
    try (FileOutputStream fos = new FileOutputStream(file)) {
      ByteBuffer byteBuffer = response.getResult().getOutput().getAudio();
      fos.write(byteBuffer.array());
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}
